<template>
  <div class='toTop' v-if='toTopShow' @click='toTop'>
    <img src='../assets/images/toTop.png'/>
  </div>
</template>
<script>
import { setInterval, clearInterval } from 'timers'
export default {
  name: 'ToTop',
  data () {
    return {
      toTopShow: 0,
      scrollTop: null
    }
  },
  mounted () {
    window.addEventListener('scroll', this.handleScroll)
  },
  methods: {
    toTop () {
      var _this = this
      var timer = setInterval(function () {
        if (_this.scrollTop) {
          _this.scrollTop -= 30
          document.documentElement.scrollTop = document.body.scrollTop = _this.scrollTop
        } else {
          clearInterval(timer)
        }
      })
    },
    handleScroll () {
      this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      this.toTopShow = this.scrollTop > 400 ? 1 : 0
    }
  }
}
</script>
<style lang="less" scoped>
.toTop{
  position:fixed;
  right:100px;
  bottom:100px;
  z-index:1000;
  width:80px;
  height:80px;
  cursor:pointer;
  img{
    width:80px;
    height:80px;
  }
}
</style>
